#include "UsrAI.h"
#include <set>
#include <iostream>
#include <unordered_map>
#include <bits/stdc++.h>
#include <map>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
tagInfo info;
//##################################一些数据结构########################################
//状态记录数组
vector<tagFarmer>idleFarmer;                //存储闲置的农民
vector<tagFarmer>fishingFarmer;             //存储捕鱼的农民（包含渔船）
vector<tagFarmer>cuttingFarmer;             //存储砍树的农民
vector<tagFarmer>buildingHomeFarmer;        //存储建造房子的农民
vector<tagFarmer>huntingFarmer;             //存储打猎的农民
vector<tagFarmer>buildingDockFarmer;        //存储造船坞的农民
vector<tagFarmer>cutStoneFarmer;            //存储采集石头的农民

vector<tagFarmer>buildFarmFarmer;           //存储正在建造农田的农民
vector<tagFarmer>buildNB_BuildingFarmer;    //存储正在建造高级建筑（不含仓库）的农民
vector<tagFarmer>buildStockFarmer;          //存储正在建造仓库的农民

//建立映射关系
map<int,int>SN_to_Sort;                     //资源映射
map<int,tagResource> SN_to_Resource;
map<int,int> FarmerStat;                    //村民SN->状态，村民状态映射

unordered_set<int> movingBoatSNs;           //记录正在移动的运输船SN
unordered_set<int> dockedBoatSNs;           //记录已靠岸的运输船SN
unordered_set<int> boardingFarmers;         //记录已下达登船命令的农民SN

void init_map(const tagInfo& info){
    SN_to_Sort.clear();
    SN_to_Resource.clear();         //每帧清空旧映射
    //每帧重新建立映射关系进行更新（用于记录种类信息）
    for(const tagResource& resource:info.resources){
        SN_to_Sort[resource.SN]=resource.Type; //资源种类的映射
        SN_to_Resource[resource.SN]=resource;   //记录资源完整信息
    }
    for(const tagBuilding& building:info.buildings){
        SN_to_Sort[building.SN]=building.Type; //建筑种类的映射
    }
}
//#####################################一些(静态)全局变量###############################
static bool isFirstAssigned=false;
static int firstHomeBuilderSN=-1;   //记录第一位建造房子的村民
static int firstDockBuilderSN=-1;   //记录第一位建造船坞的村民
static int firstHunterSN=-1;        //记录第一个打猎的村民
static int firstCutterSN=-1;        //记录第一个砍树的村民

static int theFarmSN=-1;            //记录农田的SN

static int Stage0_humanMax=13;
static int Stage1_humanMax=15;
static int currentHuman_N=4;                //最开始只有4个村民
static int fish_ship_Max=3;                 //最多3个渔船
static int boat_Max=2;                      //最多建2个运输船
static int ATShip_Max=12;                   //最多建12个战船
//判断市场对应的某些技术是否升级
static bool updateWoodFlag=false;           //判断伐木技术是否升级
static bool updateFarmFlag=false;           //判断农场是否升级
static bool updateStoneFlag=false;          //判断采集石头技术是否升级
static bool updateGoldFlag=false;           //判断采集金矿技术是否升级
//判断仓库对应技术是否升级
static bool UsetoolFlag=false;              //判断使用工具是否升级
static bool DefenseInfantryFlag=false;      //判断步兵护甲是否升级
static bool DefenseArcherFlag=false;        //判断弓兵护甲是否升级
static bool DefenseRiderFlag=false;         //判断骑兵护甲是否升级
//一些静态变量
char gameM[128][128];  // 128x128地图块
static int centerDR=-1,centerUR=-1;         //实时地图函数中初始化市政中心坐标
static int stage=0;                         //阶段控制静态变量
//判断有关军队是否产生
static bool createClubmanFlag=false;        //判断军营生产棍棒兵
static bool createSlingerFlag=false;        //判断军营生产投石兵
static bool updateClubmanFlag=false;        //判断军营升级棍棒兵为斧头兵
static bool createBowmanFlag=false;         //判断靶场生产弓箭兵
static bool createScoutFlag=false;          //判断马厩生产骑兵
//军队数量max
static int ClubmanMax=6;                    //最多6个棍棒兵/斧头兵
static int SlingerMax=4;                    //最多4个投石兵
static int BowmanMax=6;                     //最多6个弓箭兵
static int ScoutMax=2;                      //最多2个骑兵
//####################################一些辅助函数########################################
//距离计算函数
double Distance(double x1,double y1,double x2,double y2){
    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
//获取建筑规模
enum BuildingSize {
    SIZE_1x1 = 1,
    SIZE_2x2 = 2,
    SIZE_3x3 = 3,
};
BuildingSize getBuildingSize(int buildingType) {
    switch (buildingType) {
        case BUILDING_HOME:
        case BUILDING_ARROWTOWER:
        case BUILDING_DOCK:
            return SIZE_2x2;
        case BUILDING_GRANARY:
        case BUILDING_CENTER:
        case BUILDING_STOCK:
        case BUILDING_FARM:
        case BUILDING_MARKET:
        case BUILDING_ARMYCAMP:
        case BUILDING_STABLE:
        case BUILDING_RANGE:
            return SIZE_3x3;
        default: return SIZE_1x1;                  //默认1x1格
    }
}
//获取实时地图
void realtimeMap(tagInfo info) {
    //每一帧更新时重新初始化地图
    for(int dr=0;dr<128;dr++){
            for(int ur=0;ur<128;ur++){
                gameM[dr][ur]='-';
            }
        }
        //标注地形
        for (int dr=0; dr<128; dr++){
            for (int ur = 0; ur < 128; ur++){
                const tagTerrain& ter=(*info.theMap)[dr][ur];
                if(ter.type==MAPPATTERN_OCEAN){
                    gameM[dr][ur]='-';
                }
                else if (ter.type==MAPPATTERN_GRASS) {
                    gameM[dr][ur]=ter.height+'0';  // 陆地高度（0-3）
                }else{
                    gameM[dr][ur]='?';//用？表示未探索区域
                }
            }
        }
        //标记资源（资源类型+‘A’）
        for(const tagResource& res:info.resources){
            int dr=res.BlockDR;
            int ur=res.BlockUR;
            if(dr>=0&&dr<128&&ur>=0&&ur<128){
                gameM[dr][ur]='A'+(res.Type%26);  // 区分资源类型
                if(gameM[dr][ur]=='P'){
                    gameM[dr][ur+1]='P';
                    gameM[dr+1][ur]='P';
                    gameM[dr+1][ur+1]='P';
                }
            }
        }
        //标记建筑（建筑类型+‘a’）
        for (const tagBuilding& building:info.buildings) {
            int dr=building.BlockDR;
            int ur=building.BlockUR;
            // 建筑占据多个块（如房屋2x2），需标记所有占用块
            int size=(building.Type==BUILDING_HOME)?2:3;  // 房屋2x2，其他3x3
            for(int i=0;i<size;i++){
                for(int j=0;j<size;j++){
                    if(dr+i<128&&ur+j<128){
                        gameM[dr+i][ur+j]='a'+(building.Type%26);
                    }
                }
            }
        }
        //标记单位位置（‘*’）
        for (const tagFarmer& farmer:info.farmers) {
                    int dr=farmer.BlockDR;
                    int ur=farmer.BlockUR;
                    if (dr>=0&&dr<128&&ur>=0&&ur<128) {
                        gameM[dr][ur]='*';
                    }
                }
        //记录市镇中心坐标
        if (centerDR==-1) {
            for (const tagBuilding& building: info.buildings) {
                if (building.Type==BUILDING_CENTER) {
                    centerDR=building.BlockDR;
                    centerUR=building.BlockUR;
                    break;
                }
            }
        }
        /*for(int dr=0;dr<128;dr++){
            for(int ur=0;ur<128;ur++){
                cout <<gameM[dr][ur];
            }
            cout <<endl;
        }
        cout <<endl;*/
}
//查找目标建筑是否建成
bool toFindTargetBuilding(int targetBuilding,const tagInfo& info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==targetBuilding&&building.Percent==100){
            return true;
//            cout <<"找到目标建筑"<< endl;
        }
    }
    return false;
}
//查找船坞
bool toFindDock(){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            return true;
        }
    }
    return false;
}
//查询市政中心序列号
int toFindCenterSN(){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER){
            return building.SN;
        }
    }
}
//####################################一些检索函数######################################
//检查建造地点是否合适（n*n）
bool isSuitBuilding(int x,int y,int n){
    int startX=x-1;
    int startY=y-1;
    int endX=x+n;
    int endY=y+n;
    //先检查是否越界
    if(startX<0||startY<0||endX>=128||endY>=128){
        return false;
    }
    char mapFlag=gameM[x][y];
//    if(mapFlag!='0'||mapFlag!='1'||mapFlag!='2'||mapFlag!='3'){
//        return false;
//    }
    //检查陆地高度一致性
    for(int i=startX;i<=endX;i++){
        for(int j=startY;j<=endY;j++){
            if(gameM[i][j]!=mapFlag||(gameM[i][j]!='0'&&gameM[i][j]!='1'&&gameM[i][j]!='2'&&gameM[i][j]!='3')){
                return false;
            }
        }
    }
    return true;
}

//以某一中心建筑为原点开始查找n*n的陆地空地
bool toBuildHome(int& x,int& y,int centerBuildingSN,int n,tagInfo info) {
    // 查找中心建筑
    tagBuilding centerBuilding;
    bool found=false;
    for(const tagBuilding& bld:info.buildings){
        if(bld.Type==centerBuildingSN){
            centerBuilding=bld;
            found=true;
            break;
        }
    }
    if(!found){// 未找到中心建筑
        return false;
    }
    // 获取中心建筑的大小
    BuildingSize centerSize=getBuildingSize(centerBuilding.Type);
    // 计算中心坐标（取建筑中心）
    int center_x=centerBuilding.BlockDR+centerSize/2;
    int center_y=centerBuilding.BlockUR+centerSize/2;
    //搜索适合建造n*n大小的建筑
    const int misRange=3;
    const int maxRange=18;
    //第一象限
    for(int i=center_x+misRange;i<=center_x+maxRange;i++){
        for(int j=center_y+misRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第二象限
    for(int i=center_x-misRange;i>=center_x-maxRange;i--){
        for(int j=center_y+misRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第三象限
    for(int i=center_x-misRange;i>=center_x-maxRange;i--){
        for(int j=center_y-misRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第四象限
    for(int i=center_x+misRange;i<=center_x+maxRange;i++){
        for(int j=center_y-misRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    return false;
}

//检查建造船坞的地点是否都为海洋
bool isSuitDock(int x,int y){
    //先检查是否越界
    if(x<0||y<0||x+1>=128||y+1>=128){
        return false;
    }
    //判断是否为海洋
    char dock_flag=gameM[x][y];
    if(dock_flag!='-'){
        return false;
    }
    if(gameM[x+1][y]==dock_flag&&gameM[x+1][y+1]==dock_flag
            &&gameM[x][y+1]==dock_flag){
        if((gameM[x-1][y]>='0'&&gameM[x-1][y]<='3')||(gameM[x-1][y+1]>='0'&&gameM[x-1][y+1]<='3')
            ||(gameM[x+2][y]>='0'&&gameM[x+2][y]<='3')||(gameM[x+2][y+1]>='0'&&gameM[x+2][y+1]<='3')
            ||(gameM[x][y-1]>='0'&&gameM[x][y-1]<='3')||(gameM[x][y+2]>='0'&&gameM[x][y+2]<='3')
            ||(gameM[x+1][y-1]>='0'&&gameM[x+1][y-1]<='3')||(gameM[x+1][y+2]>='0'&&gameM[x+1][y+2]<='3')){
            return true;
        }
    }
//    if(gameM[x-1][y]=='P'||gameM[x-1][y+1]=='P'||gameM[x+2][y]=='P'||gameM[x+2][y+1]=='P'||
//            gameM[x][y-1]=='P'||gameM[x][y+2]=='P'||gameM[x+1][y-1]=='P'||gameM[x+1][y+2]=='P'){
//        return false;
//    }
    return false;
}

//以某一鱼塘为中心原点开始查找适合建造船坞的地点
bool toBuildDock(int& x,int& y,tagInfo info){
    //先查找鱼塘
    bool pond_flag=false;
    int pond_x=-1,pond_y=-1;    //初始化鱼塘坐标（目前还没有找到）
    for(tagResource& resource:info.resources){
        if(resource.Type==RESOURCE_FISH&&resource.Cnt>0){
            pond_x=resource.BlockDR;
            pond_y=resource.BlockUR;
            pond_flag=true;
            break;
        }
    }
    if(!pond_flag) return false;    //如果没有找到鱼塘
    const int minRange=3;
    const int maxRange=17;
    //第一象限
    for(int i=pond_x+minRange;i<=pond_x+maxRange;i++){
        for(int j=pond_y+minRange;j<=pond_y+maxRange;j++){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第二象限
    for(int i=pond_x-minRange;i>=pond_x-maxRange;i--){
        for(int j=pond_y+minRange;j<=pond_y+maxRange;j++){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第三象限
    for(int i=pond_x-minRange;i>=pond_x-maxRange;i--){
        for(int j=pond_y-minRange;j>=pond_y-maxRange;j--){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第四象限
    for(int i=pond_x+minRange;i<=pond_x+maxRange;i++){
        for(int j=pond_y-minRange;j>=pond_y-maxRange;j--){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    return false;
}

//农民状态判断函数
void judgeFarmerState(const tagInfo& info) {
    idleFarmer.clear();
    fishingFarmer.clear();
    cuttingFarmer.clear();
    huntingFarmer.clear();
    buildingHomeFarmer.clear();
    buildFarmFarmer.clear();
    buildingDockFarmer.clear();
    cutStoneFarmer.clear();
    buildNB_BuildingFarmer.clear();
    buildStockFarmer.clear();
    FarmerStat.clear();

    for(const tagFarmer& farmer:info.farmers){
        FarmerStat[farmer.SN]=farmer.NowState; // 记录状态
        if(farmer.SN==firstHomeBuilderSN||farmer.SN==firstDockBuilderSN||
           farmer.SN==firstCutterSN||farmer.SN==firstHunterSN) {
            continue;
        }

        // 对于渔船，若工作对象无效，强制标记为需要新任务
        if(farmer.FarmerSort==2){
            if(farmer.NowState==HUMAN_STATE_WORKING){
                int workSN=farmer.WorkObjectSN;
                if(SN_to_Resource.count(workSN)&&SN_to_Resource[workSN].Cnt <= 0) {
                    idleFarmer.push_back(farmer); //视为空闲，等待新任务
                    continue;
                }
            }else if(farmer.NowState==HUMAN_STATE_IDLE){
                idleFarmer.push_back(farmer);
            }
            continue;
        }

        if(farmer.NowState==HUMAN_STATE_IDLE){
            idleFarmer.push_back(farmer);
            continue;
        }else if(farmer.NowState==HUMAN_STATE_WORKING){
            int workSN=farmer.WorkObjectSN;
            if(SN_to_Sort.count(workSN)){
                int resType=SN_to_Sort[workSN];
                // 根据工作对象类型归类
                if(resType==RESOURCE_FISH&&farmer.FarmerSort==2){
                    fishingFarmer.push_back(farmer);
                }else if(resType==RESOURCE_TREE&&farmer.FarmerSort==0){
                    cuttingFarmer.push_back(farmer);
                }else if(resType==RESOURCE_GAZELLE&&farmer.FarmerSort==0){
                    huntingFarmer.push_back(farmer);
                }else if(resType==BUILDING_HOME&&farmer.FarmerSort==0){
                    buildingHomeFarmer.push_back(farmer);
                }else if(resType==BUILDING_DOCK&&farmer.FarmerSort==0){
                    buildingDockFarmer.push_back(farmer);
                }else if(resType==RESOURCE_STONE&&farmer.FarmerSort==0){
                    cutStoneFarmer.push_back(farmer);
                }else if(resType==BUILDING_FARM&&farmer.FarmerSort==0){
                    buildFarmFarmer.push_back(farmer);
                }else if((resType==BUILDING_MARKET||resType==BUILDING_GRANARY)&&farmer.FarmerSort==0){
                    buildNB_BuildingFarmer.push_back(farmer);
                }else if(resType==BUILDING_STOCK&&farmer.FarmerSort==0){
                    buildStockFarmer.push_back(farmer);
                }
            }
        }
    }
}

//寻找最近的资源（返回最近的目标资源种类序列号）
int findResource(const tagFarmer& farmer,int targetType,const tagInfo& info){
        double minDis=1e12;
        int closestSN=-1;
        double tempDis;
        // 遍历所有资源
        for(const tagResource& resource:info.resources){
            if(resource.Type!=targetType){
                continue;
            }
            if(resource.Cnt<=0){
                continue;
            }
            if(resource.BlockDR<0||resource.BlockDR>=128||resource.BlockUR<0||resource.BlockUR>=128){
                continue;
            }
            const tagTerrain& terrain=(*info.theMap)[resource.BlockDR][resource.BlockUR];
            if(terrain.type==MAPPATTERN_UNKNOWN){
                continue;
            }
            tempDis=Distance(farmer.DR,farmer.UR,resource.DR,resource.UR);
            // 更新最近资源
            if(tempDis<minDis){
                minDis=tempDis;
                closestSN=resource.SN;
            }
        }
        return closestSN;
}
//#####################################任务分配函数###########################################
//判断是否还有瞪羚剩余
bool isGazelle(const tagInfo& info){
    for(const tagResource& resource:info.resources){
        if(resource.Type==RESOURCE_GAZELLE&&resource.Cnt>=0){
            return true;
        }
    }
    return false;
}

//对最开始的4位村民进行任务分配
void UsrAI::assignFirstTask(const tagInfo &info){
    if(isFirstAssigned||info.farmers.size()!=4) return;
    for(int i=0;i<4;i++){
        const tagFarmer& myFarmer=info.farmers[i];
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        if(i==0&&myFarmer.FarmerSort==0){   //让第一位村民建房子
            int x,y;
            if(toBuildHome(x,y,BUILDING_CENTER,2,info)&&info.Wood>=BUILD_HOUSE_WOOD){
                HumanBuild(myFarmer.SN,BUILDING_HOME,x,y);
                firstHomeBuilderSN=myFarmer.SN;
            }
        }else if(i==1&&myFarmer.FarmerSort==0){   //让第二个村民造船坞
            int dockX,dockY;
            if(toBuildDock(dockX,dockY,info)&&info.Wood>=BUILD_DOCK_WOOD){
                HumanBuild(myFarmer.SN,BUILDING_DOCK,dockX,dockY);
                firstDockBuilderSN=myFarmer.SN;
            }
        }else if(i==2&&myFarmer.FarmerSort==0){   //第三个村民去砍树
            int treeSN=-1;
            treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
                firstCutterSN=myFarmer.SN;
            }
        }else if(i==3&&myFarmer.FarmerSort==0){     //让第四个村民去打猎
             int huntSN=-1;
             huntSN=findResource(myFarmer,RESOURCE_GAZELLE,info);
             if(huntSN!=-1){
                 HumanAction(myFarmer.SN,huntSN);
                 firstHunterSN=myFarmer.SN;
             }
        }
    }
    isFirstAssigned=true;
}
//##########################################检索各种船的数量####################################
//检索渔船数量
bool isToBuildFish_ship(const tagInfo& info){
    bool toBuildFishShip_flag=false;
    int currentFishShip_N=0;
    for(const tagFarmer& fishFaremer:info.farmers){
        if(fishFaremer.FarmerSort==2){
            currentFishShip_N++;
        }
    }
    if(currentFishShip_N<fish_ship_Max){
        toBuildFishShip_flag=true;
    }
    return toBuildFishShip_flag;
}
//检索运输船数量
bool isToBuildBoat(const tagInfo& info){
    bool toBuildBoat_flag=false;
    int currentBoat_N=0;
    for(const tagFarmer& boat:info.farmers){
        if(boat.FarmerSort==1){
            currentBoat_N++;
        }
    }
    if(currentBoat_N<boat_Max){
        toBuildBoat_flag=true;
    }
    return toBuildBoat_flag;
}
//检索战船数量
bool isToBuildATShip(const tagInfo& info){
    bool toBuildATShip_flag=false;
    int currentATShip_N=0;
    for(const tagArmy& warship:info.armies){
        if(warship.Sort==7){
            currentATShip_N++;
        }
    }
    if(currentATShip_N<ATShip_Max){
        toBuildATShip_flag=true;
    }
    return toBuildATShip_flag;
}
//#############################################################################################
//最开始打猎和砍树的村民继续之前的任务
void UsrAI::goWork_hunt(const tagInfo &info){
    if(firstHunterSN==-1) return;
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstHunterSN&&farmer.NowState==HUMAN_STATE_IDLE){
            if(isGazelle(info)){
                int nextGazelle=findResource(farmer,RESOURCE_GAZELLE,info);
                if(nextGazelle!=-1){
                    HumanAction(farmer.SN,nextGazelle);
                }
            }else{
                int nextTreeSN=findResource(farmer,RESOURCE_TREE,info);
                if(nextTreeSN!=-1){
                    HumanAction(farmer.SN,nextTreeSN);
                }
            }
        }
        break;
    }
}
void UsrAI::goWork_cut(const tagInfo &info){
    if(firstCutterSN==-1) return;
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstCutterSN&&farmer.NowState==HUMAN_STATE_IDLE){
            int nextTreeSN=findResource(farmer,RESOURCE_TREE,info);
            if(nextTreeSN!=-1){
                HumanAction(farmer.SN,nextTreeSN);
            }
        }
        break;
    }
}

//让最开始建房子和建造船坞的村民继续建造其他建筑
bool isGoWork(int buildType,const tagInfo& info,int num_max){
    int currentNum=0;
    for (const auto& bld:info.buildings) {
        if(bld.Type==buildType&&bld.Percent==100){
            currentNum++;
        }
    }
    if(buildType==BUILDING_HOME){
        return currentNum<num_max;//最多home_max个房子
    }else if(buildType==BUILDING_DOCK){
        return currentNum<num_max;//最多两个船坞
    }else if(buildType==BUILDING_GRANARY){
        return currentNum<num_max;//最多一个谷仓
    }else if(buildType==BUILDING_FARM){
        return currentNum<num_max;//最多一个农田
    }else if(buildType==BUILDING_MARKET){
        return currentNum<num_max;//最多一个市场
    }else if(buildType==BUILDING_STOCK){
        return currentNum<num_max;//最多两个仓库
    }else if(buildType==BUILDING_ARMYCAMP){
        return currentNum<num_max;//最多两个军营
    }
    return false;
}
void UsrAI::goWork_build_dock(const tagInfo& info,int num_max) {
    int num=num_max;
    //继续建船坞
    if (firstDockBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE) {
                if(info.Wood>=BUILD_DOCK_WOOD&&isGoWork(BUILDING_DOCK,info,num)) {
                    int dockX,dockY;
                    if (toBuildDock(dockX,dockY,info)) {
                        HumanBuild(farmer.SN,BUILDING_DOCK,dockX,dockY);
                    }
                }
                break;
            }
        }
    }   
}
void UsrAI::goWork_build_home(const tagInfo& info,int num_max){
    int num=num_max;
    //继续建房子
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(info.Wood>=BUILD_HOUSE_WOOD&&isGoWork(BUILDING_HOME,info,num)){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,2,info)){
                        HumanBuild(farmer.SN,BUILDING_HOME,x,y);
                    }
                }
                break;
            }
        }
    }
}

//stage1中让建造船坞的村民去建房屋（任务转换）
void UsrAI::buildDockToBuildhome(const tagInfo &info,int num_max){
    int num=num_max;
    if(firstDockBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN){
                if(farmer.NowState==HUMAN_STATE_IDLE&&info.Wood>=BUILD_HOUSE_WOOD&&isGoWork(BUILDING_HOME,info,num)){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,2,info)){
                        HumanBuild(farmer.SN,BUILDING_HOME,x,y);
                    }
                }
            }
            break;
        }
    }
}
//stage2中firstDockBuilderSN建造完房屋后去采集石头
void UsrAI::buildDockToBuildhomeToStone(const tagInfo &info, int num_max){
    int num=num_max,stoneSN=-1;
    if(firstDockBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN){
                if(farmer.NowState==HUMAN_STATE_IDLE&&!isGoWork(BUILDING_HOME,info,num)){
                    stoneSN=findResource(farmer,RESOURCE_STONE,info);
                    if(stoneSN!=-1){
                        HumanAction(farmer.SN,stoneSN);
                    }
                }
            }
        }
    }
}

//不断地分配任务
void UsrAI::assignNewTask(const tagInfo &info){
    for(const tagFarmer& myFarmer:info.farmers){
        if(myFarmer.FarmerSort!=0) continue;
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        //跳过初始村民
        if(myFarmer.SN==firstHomeBuilderSN||myFarmer.SN==firstDockBuilderSN ||
           myFarmer.SN==firstCutterSN||myFarmer.SN==firstHunterSN) {
                    continue;
         }
        if(isGazelle(info)){
            int flag=rand()%2;  //flag=0砍树/1打猎
            if(flag==1&&huntingFarmer.size()<4){
                int huntSN=findResource(myFarmer,RESOURCE_GAZELLE,info);
                if(huntSN!=-1){
                    HumanAction(myFarmer.SN,huntSN);
                }
            }else if(flag==0&&cuttingFarmer.size()<14){
                int treeSN=findResource(myFarmer,RESOURCE_TREE,info);
                if(treeSN!=-1){
                    HumanAction(myFarmer.SN,treeSN);
                }
            }
        }else{      //如果瞪羚耗尽了，全部去砍树
            int treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
            }
        }
    }
}
//stage0后的持续任务分配（除了初始的全部去砍树）
void UsrAI::assignNewTaskAfterStage0(const tagInfo &info){
    for(const tagFarmer& myFarmer:info.farmers){
        if(myFarmer.FarmerSort!=0) continue;
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        //跳过初始村民
        if(myFarmer.SN==firstHomeBuilderSN||myFarmer.SN==firstDockBuilderSN||myFarmer.SN==firstCutterSN){
            continue;
         }
        //除了初始的全部去砍树
        if(cuttingFarmer.size()<15){
            int treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
            }
        }
    }
}
//####################################stage1中的任务分配###################################
//指定数量为num的村民去砍树
void UsrAI::farmerToCut(const tagInfo &info,int num){
    int need=num-cuttingFarmer.size();
    if(need<=0) return;

    int treeSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            treeSN=findResource(farmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(farmer.SN,treeSN);
                assigned++;
            }
        }
    }
}
//指定数量为num的村民打猎
void UsrAI::farmerToHunt(const tagInfo &info,int num){
    int need=num-huntingFarmer.size();
    if(need<=0) return;

    int gazelleSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            gazelleSN=findResource(farmer,RESOURCE_GAZELLE,info);
            if(gazelleSN!=-1){
                HumanAction(farmer.SN,gazelleSN);
                assigned++;
            }
        }
    }
}
//指定数量为num的村民采集石头
void UsrAI::farmerToStone(const tagInfo &info,int num){
    int need=num-cutStoneFarmer.size();
    if(need<=0) return;

    int stoneSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            stoneSN=findResource(farmer,RESOURCE_STONE,info);
            if(stoneSN!=-1){
                HumanAction(farmer.SN,stoneSN);
                assigned++;
            }
        }
    }
}
//stage2中让一位村民去建造农田
void UsrAI::farmerToBuildFarmAfterStage0(const tagInfo &info, int num){
    int need=num-buildFarmFarmer.size();
    if(need<=0) return;

    int assigned=0;
    for(const tagFarmer& farmer:info.farmers){
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            int x,y;
            if(info.Wood>=BUILD_FARM_WOOD&&isGoWork(BUILDING_FARM,info,2)){
                if(toBuildHome(x,y,BUILDING_CENTER,3,info)){
                    HumanBuild(farmer.SN,BUILDING_FARM,x,y);
                    assigned++;
                }
            }
            break;
        }
    }

}

//让最开始建造船坞的村民在建完dock_num个船坞后去砍树
void UsrAI::buildDockToCut(const tagInfo &info,int dock_num){
    int treeSN=-1;
    if(firstDockBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(!isGoWork(BUILDING_DOCK,info,dock_num)){
                    treeSN=findResource(farmer,RESOURCE_TREE,info);
                    if(treeSN!=-1){
                        HumanAction(farmer.SN,treeSN);
                    }
                }
            }
        }
    }
}

//让建房屋的村民在完成阶段任务后去砍树
void UsrAI::buildHomeToCut(const tagInfo &info,int stage0_home_max){
    int treeSN=-1;
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(!isGoWork(BUILDING_HOME,info,stage0_home_max)){
                    treeSN=findResource(farmer,RESOURCE_TREE,info);
                    if(treeSN!=-1){
                        HumanAction(farmer.SN,treeSN);
                    }
                }
            }
        }
    }
}

//建造高级的建筑(3*3),由最开始建房子的村民去建造(相当于检测5*5)
void UsrAI::buildNB_buildings(const tagInfo& info,int targetBuilding,int num_max){
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN){
                if(farmer.NowState==HUMAN_STATE_IDLE){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,3,info)&&isGoWork(targetBuilding,info,num_max)){
                        HumanBuild(farmer.SN,targetBuilding,x,y);
                    }
                }
            }
        }
    }
}
//########################################################################################
//查询农田SN
int findFarmSN(const tagInfo& info){
    int farmSN=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_FARM&&building.Percent==100){
            farmSN=building.SN;
        }
    }
    return farmSN;
}
//继续种地
void UsrAI::goWork_farming(const tagInfo &info){
    theFarmSN=findFarmSN(info);
    if(firstHomeBuilderSN!=-1&&theFarmSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                HumanAction(farmer.SN,theFarmSN);
            }
        }
    }
}
//#####################################船坞的一些动作#######################################
//船坞造渔船
void UsrAI::buildFish_ship(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& bld:info.buildings){
        if(bld.Type==BUILDING_DOCK&&bld.Percent==100){
            dockSN=bld.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_SAILING);
    }
}
//渔船捕鱼
void UsrAI::ship_to_fish(const tagInfo &info){
    unordered_set<int> assignedFishSNs;             //记录当前已分配的鱼资源SN，避免重复分配
    for(const tagFarmer& boat:info.farmers){
        if(boat.FarmerSort!=2||boat.NowState!=HUMAN_STATE_IDLE){
            continue;                               //非渔民或非空闲状态，跳过
        }
        //寻找最近的、未分配的、有效鱼资源
        int min_SN=-1;
        double min_dis=1e9;
        for(const tagResource& resource:info.resources) {
            if (resource.Type!=RESOURCE_FISH) continue;
            if (resource.Cnt<=0) continue;                          //资源未耗尽
            if (assignedFishSNs.count(resource.SN)) continue;       //未被当前轮次的其他渔民分配
            //计算渔民到鱼资源的距离
            double dis=Distance(boat.DR, boat.UR, resource.DR, resource.UR);
            if (dis<min_dis) {
                min_dis=dis;
                min_SN=resource.SN;
            }
        }
        //若找到有效资源，分配任务并标记为已分配
        if(min_SN!=-1){
            HumanAction(boat.SN, min_SN);
            assignedFishSNs.insert(min_SN); //将资源SN加入已分配集合
        }
    }
}
//船坞造运输船
void UsrAI::buildBoat(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& bld:info.buildings){
        if(bld.Type==BUILDING_DOCK&&bld.Percent==100){
            dockSN=bld.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_WOOD_BOAT);
    }
}
//船坞造战船
void UsrAI::buildATShip(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& bld:info.buildings){
        if(bld.Type==BUILDING_DOCK&&bld.Percent==100){
            dockSN=bld.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_SHIP);
    }
}
//###################################战船的一些动作#########################################
//自动锁敌攻击敌军
void UsrAI::fightingEnermy(const tagInfo &info){
    int enemyshipSN=-1;
    for(const tagArmy& enemy_ship:info.enemy_armies){
        if(enemy_ship.Sort==AT_SHIP){
            enemyshipSN=enemy_ship.SN;
            break;
        }
    }
    for(const tagArmy& ourShip:info.armies){
        if(ourShip.Sort==AT_SHIP&&ourShip.NowState==HUMAN_STATE_IDLE){
            HumanAction(ourShip.SN,enemyshipSN);
            break;
        }
    }
}
//寻找敌方大陆坐标
void UsrAI::findEnermyRoute(const tagInfo &info,int& enermyLand_x,int& enermyLand_y){
    enermyLand_x=-1;
    enermyLand_y=-1;
    int x=-1,y=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER){
            x=building.BlockDR;
            y=building.BlockUR;
            break;
        }
    }
    enermyLand_x=(x<64)?100:25;
    enermyLand_y=(y<64)?100:25;
}
//战船前往敌方大陆
void UsrAI::moveToEnermyLand(const tagInfo &info){
    int enermyLand_x=-1,enermyLand_y=-1;
    findEnermyRoute(info,enermyLand_x,enermyLand_y);
    for(const tagArmy& ourShip:info.armies){
        if(ourShip.Sort==AT_SHIP&&ourShip.NowState==HUMAN_STATE_IDLE){
            HumanMove(ourShip.SN,enermyLand_x*BLOCKSIDELENGTH,enermyLand_y*BLOCKSIDELENGTH);
        }
    }
}

//######################################运输船的动作###########################################
//运输船寻找敌方大陆坐标
void UsrAI::boatFindEnermyLand(const tagInfo &info,int &enermyLand_x,int &enermyLand_y){
    enermyLand_x=-1;
    enermyLand_y=-1;
    int x=-1,y=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER){
            x=building.BlockDR;
            y=building.BlockUR;
            break;
        }
    }
    enermyLand_x=(x<64)?103:23;
    enermyLand_y=(y<64)?103:23;
}
//运输船前往敌方大陆
void UsrAI::boatMoveToEnermyLand(const tagInfo &info){
    int enermyLand_x=-1,enermyLand_y=-1;
    boatFindEnermyLand(info,enermyLand_x,enermyLand_y);
    for(const tagFarmer& ourBoat:info.farmers){
        if(ourBoat.FarmerSort==1&&ourBoat.NowState==HUMAN_STATE_IDLE){
            HumanMove(ourBoat.SN,enermyLand_x*BLOCKSIDELENGTH,enermyLand_y*BLOCKSIDELENGTH);
        }
    }
}
//######################################运输船进行靠岸#########################################
//获取已有运输船的坐标（避免运输船之间位置太近）
vector<pair<int,int>> getBoatPos(const tagInfo& info){
    vector<pair<int,int>> pos;
    for(const tagFarmer& myBoat:info.farmers){
        if(myBoat.FarmerSort==1){
            pos.emplace_back(myBoat.BlockDR,myBoat.BlockUR);
        }
    }
    return pos;
}
//检索船坞的坐标
pair<int,int> findDockPos(const tagInfo& info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            return {building.BlockDR,building.BlockUR};
        }
    }
    return {-1,-1};                                                 //未找到
}
//检索船坞附近的沿岸坐标
pair<int,int> findNearLandPosForBoat(const tagInfo& info,int dockDR,int dockUR,const vector<pair<int,int>>& usePos){
    const int findRange=5;
    const int safeDistance=3;
    vector<pair<int,int>> candidates; // 【新增】存储所有符合条件的候选位置
    for(int x=dockDR-findRange;x<=dockDR+findRange;x++){
        for(int y=dockUR-findRange;y<=dockUR+findRange;y++){
            if(x<0||x>=128||y<0||y>=128) continue;                  //越界检查
            if(gameM[x][y]!='-') continue;                          //检查是否为海洋
            //防重叠检测
            bool isOccupied=false;
            for(const auto& position:usePos){
                int dx=abs(x-position.first);
                int dy=abs(y-position.second);
                if(dx<safeDistance&&dy<safeDistance){
                    isOccupied=true;
                    break;
                }
            }
            if(isOccupied) continue;
            //检查是否沿岸
            bool isNearLand=false;
            for(int i=x-1;i<=x+1;i++){
                for(int j=y-1;j<=y+1;j++){
                    if(i<0||i>=128||j<0||j>=128) continue;
                    if(i==x&&j==y) continue;
                    if(gameM[i][j]>='0'&&gameM[i][j]<='3'){
                        isNearLand=true;
                        break;
                    }
                }
                if(isNearLand) break;
            }
            if(isNearLand){
                candidates.emplace_back(x,y);                           //符合条件的位置加入候选列表
            }
        }
    }
    //从候选位置中筛选出离陆地最近的位置
        if(candidates.empty()){
            return {-1,-1};                                             //无符合条件的位置
        }

        pair<int,int> bestPos={-1,-1};
        int minDistance=INT_MAX;                                        //记录最近距离（曼哈顿距离）

        for(const auto& pos:candidates){
            int x=pos.first;
            int y=pos.second;
            int currentMin=INT_MAX;

            //计算当前位置到最近陆地的曼哈顿距离
            for(int i=x-2;i<=x+2;i++){                                  //扩大搜索范围确保找到最近陆地
                for(int j=y-2;j<=y+2;j++){
                    if(i<0||i>=128||j<0||j>=128) continue;
                    if(gameM[i][j]>='0'&&gameM[i][j]<='3'){
                        int dist=abs(x-i)+abs(y-j);                     //曼哈顿距离
                        if(dist<currentMin){
                            currentMin=dist;
                        }
                    }
                }
            }

            //更新最近陆地的位置
            if(currentMin<minDistance){
                minDistance=currentMin;
                bestPos=pos;
            }
        }
        return bestPos;                                                 //返回离陆地最近的位置
}
//运输船移动至己方大陆沿岸
void UsrAI::boatMoveToNearLand(const tagInfo& info){
    //处理已移动的船，检测是否到达
    vector<int> arrivedBoats; //记录已到达的船（从集合中移除）
    for(int sn:movingBoatSNs){
        bool found=false;
        for(const tagFarmer& boat:info.farmers){
            if(boat.SN==sn){
                found=true;
                //若运输船变回空闲状态，看作到达
                if(boat.NowState==HUMAN_STATE_IDLE){
                    arrivedBoats.push_back(sn);
                }
                break;
            }
        }
        if(!found){
            arrivedBoats.push_back(sn); //船可能被销毁，强制移除
        }
    }
    //移除已到达的船
    for(int sn:arrivedBoats){
        movingBoatSNs.erase(sn);
        dockedBoatSNs.insert(sn);       //标记已停靠的运输船
    }
    //查找没有移动的运输船
    int targetBoatSN=-1;
    for(const tagFarmer& myBoat:info.farmers){
        if(myBoat.FarmerSort==1&&myBoat.NowState==HUMAN_STATE_IDLE&&!movingBoatSNs.count(myBoat.SN)&&!dockedBoatSNs.count(myBoat.SN)){
            targetBoatSN=myBoat.SN;
            break;
        }
    }
    pair<int,int> dockPos=findDockPos(info);
    int dockDR=dockPos.first;
    int dockUR=dockPos.second;
    //获取运输船坐标
    vector<pair<int,int>> boatPosition=getBoatPos(info);

    pair<int,int> nearLandPos=findNearLandPosForBoat(info,dockDR,dockUR,boatPosition);
    int nearLandDR=nearLandPos.first;
    int nearLandUR=nearLandPos.second;

    double nearLandx=nearLandDR*BLOCKSIDELENGTH+BLOCKSIDELENGTH/2.0;
    double nearLandy=nearLandUR*BLOCKSIDELENGTH+BLOCKSIDELENGTH/2.0;
    HumanMove(targetBoatSN,nearLandx,nearLandy);
    //加入移动集合
    movingBoatSNs.insert(targetBoatSN);
}
//######################################市镇中心的动作##########################################
//市镇中心生产新的村民
void UsrAI::createFarmer(const tagInfo& info,int stage_human_max){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=BUILDING_CENTER_CREATEFARMER_FOOD
           &&info.farmers.size()<=stage_human_max+boat_Max+fish_ship_Max){
            BuildingAction(building.SN,BUILDING_CENTER_CREATEFARMER);
        }
    }
}
//市镇中心升级时代
void UsrAI::updateAge(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=500&&
                info.farmers.size()>=Stage0_humanMax){
            BuildingAction(building.SN,BUILDING_CENTER_UPGRADE);
        }
        break;
    }
}
//######################################市场的一些动作############################################
//升级伐木技术
void UsrAI::updateWood(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Wood>=BUILDING_MARKET_WOOD_UPGRADE_WOOD&&info.Meat>=BUILDING_MARKET_WOOD_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_WOOD_UPGRADE);
                updateWoodFlag=true;
            }
        }
    }
}
//提高农田容量
void UsrAI::updateFarm(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Wood>=BUILDING_MARKET_FARM_UPGRADE_WOOD&&info.Meat>=BUILDING_MARKET_FARM_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_FARM_UPGRADE);
                updateFarmFlag=true;
            }
        }
    }
}
//升级采集石头的技术
void UsrAI::updateStone(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Stone>=BUILDING_MARKET_STONE_UPGRADE_STONE&&info.Meat>=BUILDING_MARKET_STONE_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_STONE_UPGRADE);
                updateStoneFlag=true;
            }
        }
    }
}
//升级采集金矿的技术
void UsrAI::updateGold(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Meat>=BUILDING_MARKET_GOLD_UPGRADE_FOOD&&info.Wood>=BUILDING_MARKET_GOLD_UPGRADE_WOOD){
                BuildingAction(building.SN,BUILDING_MARKET_GOLD_UPGRADE);
                updateGoldFlag=true;
            }
        }
    }
}
//######################################仓库的一些动作############################################
//仓库升级使用工具
void UsrAI::updateUsetool(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_USETOOL_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_USETOOL);
                UsetoolFlag=true;
            }
        }
    }
}
//仓库升级步兵护甲
void UsrAI::updateDefenseInfantry(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY);
                DefenseInfantryFlag=true;
            }
        }
    }
}
//仓库升级弓兵护甲
void UsrAI::updateDefenceArcher(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER);
                DefenseArcherFlag=true;
            }
        }
    }
}
//仓库升级骑兵护甲
void UsrAI::updateDefenceRider(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_RIDER_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_RIDER);
                DefenseRiderFlag=true;
            }
        }
    }
}
//##################################判断军营等建筑是否继续生产#####################################
//判断是否继续生产棍棒兵/斧头兵
bool isToCreateClubman(const tagInfo& info){
    bool toCreateClubmanFlag=false;
    int currentClubman_N=0;
    for(const tagArmy& ourClubman:info.armies){
        if(ourClubman.Sort==AT_CLUBMAN){
            currentClubman_N++;
        }
    }
    if(currentClubman_N<ClubmanMax){
        toCreateClubmanFlag=true;
    }
    return toCreateClubmanFlag;
}
//判断是否继续生产投石兵
bool isToCreateSlinger(const tagInfo& info){
    bool toCreateSlingerFlag=false;
    int currentSlinger_N=0;
    for(const tagArmy& ourSlinger:info.armies){
        if(ourSlinger.Sort==AT_SLINGER){
            currentSlinger_N++;
        }
    }
    if(currentSlinger_N<SlingerMax){
        toCreateSlingerFlag=true;
    }
    return toCreateSlingerFlag;
}
//判断是否继续生产弓箭兵
bool isToCreateBowman(const tagInfo& info){
    bool toCreateBowmanFlag=false;
    int currentBowman_N=0;
    for(const tagArmy& ourBowman:info.armies){
        if(ourBowman.Sort==AT_BOWMAN){
            currentBowman_N++;
        }
    }
    if(currentBowman_N<BowmanMax){
        toCreateBowmanFlag=true;
    }
    return toCreateBowmanFlag;
}
//判断是否继续生产骑兵
bool isToCreateScout(const tagInfo& info){
    bool toCreateScoutFlag=false;
    int currentScout_N=0;
    for(const tagArmy& ourScout:info.armies){
        if(ourScout.Sort==AT_SCOUT){
            currentScout_N++;
        }
    }
    if(currentScout_N<ScoutMax){
        toCreateScoutFlag=true;
    }
    return toCreateScoutFlag;
}
//#####################################军营等建筑生产军队#########################################
//军营生产棍棒兵/斧头兵
void UsrAI::ArmycampCreateClubman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&isToCreateClubman(info)&&info.Meat>=BUILDING_ARMYCAMP_CREATE_CLUBMAN_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_CREATE_CLUBMAN);
                createClubmanFlag=true;
            }
        }
    }
}
//军营生产投石兵
void UsrAI::ArmycampCreateSlinger(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&isToCreateSlinger(info)
                    &&info.Stone>=BUILDING_ARMYCAMP_CREATE_SLINGER_STONE&&info.Meat>=BUILDING_ARMYCAMP_CREATE_SLINGER_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_CREATE_SLINGER);
                createSlingerFlag=true;
            }
        }
    }
}
//军营将棍棒兵升级为斧头兵
void UsrAI::ArmycampUpdateClubman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&info.Meat>=BUILDING_ARMYCAMP_UPGRADE_CLUBMAN_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_UPGRADE_CLUBMAN);
                updateClubmanFlag=true;
            }
        }
    }
}
//靶场生产弓箭兵
void UsrAI::RangeCreateBowman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_RANGE&&building.Percent==100){
            if(building.Project==0&&isToCreateBowman(info)&&info.Meat>=BUILDING_RANGE_CREATE_BOWMAN_FOOD
                    &&info.Wood>=BUILDING_RANGE_CREATE_BOWMAN_WOOD){
                BuildingAction(building.SN,BUILDING_RANGE_CREATE_BOWMAN);
                createBowmanFlag=true;
            }
        }
    }
}
//马厩生产骑兵
void UsrAI::StableCreateScout(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STABLE&&building.Percent==100){
            if(building.Project==0&&isToCreateScout(info)&&info.Meat>=BUILDING_STABLE_CREATE_SCOUT_FOOD){
                BuildingAction(building.SN,BUILDING_STABLE_CREATE_SCOUT);
                createScoutFlag=true;
            }
        }
    }
}
//######################################村民上岸后的动作##########################################
//村民上岸后寻路探索函数

//#########################################村民登船##############################################
//村民登船
void UsrAI::farmerBoardToBoat(const tagInfo &info){
    vector<int> suitableBoat;                               //记录空闲且靠岸的运输船
    for(const tagFarmer& ourBoat:info.farmers){
        if(ourBoat.FarmerSort==1&&dockedBoatSNs.count(ourBoat.SN)
           &&ourBoat.NowState==HUMAN_STATE_IDLE&&ourBoat.Resource<5){
            suitableBoat.push_back(ourBoat.SN);
        }
    }
    if(suitableBoat.empty()){
        DebugText("运输船未停靠或已载满，目前无可用运输船！");
        return;
    }

    vector<int> suitableForBoardFarmers;                            //记录适合登船的农民
    for(const tagFarmer& toBoardFarmer:info.farmers){
//        if(toBoardFarmer.SN==firstHomeBuilderSN) continue;
//        if(toBoardFarmer.SN==firstDockBuilderSN) continue;
//        if(toBoardFarmer.FarmerSort==0&&toBoardFarmer.NowState==HUMAN_STATE_IDLE&&!boardingFarmers.count(toBoardFarmer.SN)){
//            suitableForBoardFarmers.push_back(toBoardFarmer.SN);
//        }
        if(toBoardFarmer.SN==firstDockBuilderSN){
            DebugText("排除不登船的村民SN: " + to_string(toBoardFarmer.SN));
            continue;
        }
        if(toBoardFarmer.SN==firstHomeBuilderSN){
            DebugText("排除不登船的村民SN: " + to_string(toBoardFarmer.SN));
            continue;
        }
        if(toBoardFarmer.SN==firstHunterSN){
            DebugText("排除不登船的村民SN: " + to_string(toBoardFarmer.SN));
            continue;
        }
        if(toBoardFarmer.SN==firstCutterSN){
            DebugText("排除不登船的村民SN: " + to_string(toBoardFarmer.SN));
            continue;
        }
        if(toBoardFarmer.FarmerSort!=0) continue;
        if(toBoardFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        if(boardingFarmers.count(toBoardFarmer.SN)) continue;

        suitableForBoardFarmers.push_back(toBoardFarmer.SN);
    }

    //分配村民登船
    int farmerNuminBoat=0;
    for(int boatSNs:suitableBoat){
        //查询当前运输船载人量
        int currentLoad=0;
        for(const tagFarmer& ourBoat:info.farmers){
            if(ourBoat.SN==boatSNs){
                currentLoad=ourBoat.Resource;
                break;
            }
        }

        while(currentLoad<5&&farmerNuminBoat<suitableForBoardFarmers.size()){
            int farmerSN=suitableForBoardFarmers[farmerNuminBoat];
            //进行登船
            HumanAction(farmerSN,boatSNs);
            DebugText("村民"+to_string(farmerSN)+"登上运输船"+to_string(boatSNs));

            //标记为已下达命令，避免重复下指令
            boardingFarmers.insert(farmerSN);
            currentLoad++;
            farmerNuminBoat++;
        }
    }
}
//######################################AI接口(主函数)###########################################
void UsrAI::processData()
{
    tagInfo info=getInfo();         //获取每帧的信息
    realtimeMap(info);              //每帧获取一次实时地图
    init_map(info);                 //资源映射更新
    judgeFarmerState(info);         //每帧更新一次村民状态
    //通过switch语句进行阶段划分
    switch(stage){
        case 0://资源累积
            assignFirstTask(info);                              //初始任务分配
            buildDockToCut(info,1);                             //建造完一个船坞后去砍树
            goWork_build_dock(info,2);                          //让起初建造船坞的继续
            buildDockToCut(info,2);                             //建造完两个船坞后去砍树
            goWork_build_home(info,6);                          //让起初建造房子的继续
            goWork_cut(info);                                   //初始砍树农民继续砍树
            goWork_hunt(info);                                  //初始打猎农民继续打猎
            assignNewTask(info);                                //分配新任务
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                           //建造渔船
            }
            ship_to_fish(info);                                 //渔船捕鱼
            buildHomeToCut(info,6);                             //建造完stage0的房屋后去砍树
            createFarmer(info,Stage0_humanMax);                 //生产新的村民
            updateAge(info);                                    //市镇中心升级时代
            if(info.civilizationStage==CIVILIZATION_TOOLAGE){
                stage=1;
                DebugText("时代升级完成，进入stage1");
            }
            break;
        case 1:            
            goWork_cut(info);                               //初始砍树农民继续砍树
            goWork_hunt(info);                              //初始打猎农民继续打猎
            goWork_build_dock(info,2);                      //如果第一阶段没有建造两个，则该阶段继续
            buildDockToBuildhome(info,12);                  //建造12个房屋
            assignNewTaskAfterStage0(info);                 //分配新任务
            createFarmer(info,Stage1_humanMax);             //生产点人口
            ship_to_fish(info);                             //渔船捕鱼
            if(isToBuildATShip(info)){
                buildATShip(info);                          //建造战船
            }
            if(!isToBuildATShip(info)){
                moveToEnermyLand(info);
                fightingEnermy(info);                       //战船寻路并攻击敌方战船
            }
            //建造一些高级建筑
            if(info.Wood>=BUILD_GRANARY_WOOD){
                buildNB_buildings(info,BUILDING_GRANARY,1);         //建造谷仓
            }
            if(info.Wood>=BUILD_MARKET_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)){
                buildNB_buildings(info,BUILDING_MARKET,1);          //建造市场
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateWood(info);                                   //升级伐木技术
            }
            if(info.Wood>=BUILD_FARM_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)&&toFindTargetBuilding(BUILDING_MARKET,info)){
                 buildNB_buildings(info,BUILDING_FARM,1);           //建造农田
            }
            if(!isGoWork(BUILDING_HOME,info,12)&&isGoWork(BUILDING_FARM,info,2)){
                farmerToBuildFarmAfterStage0(info,2);               //firstDockBuilderSN再建造农田
            }
//            //一系列技术升级完成后，建造运输船（骑兵护甲和弓兵护甲stage2升级）
//            if(updateWoodFlag&&toFindTargetBuilding(BUILDING_FARM,info)&&(!isToBuildATShip(info))){
//                if(isToBuildBoat(info)){
//                    buildBoat(info);
//                }
//            }
//            boatMoveToNearLand(info);                                   //运输船靠岸
//            //运输船建造完毕，进入stage2
//            if(!isToBuildBoat(info)){
//                stage=2;
//                DebugText("运输船建造完成，进入stage2！");
//            }
            //战船建造完毕，进入stage2
            if(!isToBuildATShip(info)){
                stage=2;
                DebugText("战船建造完毕，进入stage2，开始进攻敌方海军！");
            }
            break;
        case 2:
            farmerToStone(info,2);                                      //采集石头
            if(!isGoWork(BUILDING_HOME,info,12)&&isGoWork(BUILDING_FARM,info,2)){
                farmerToBuildFarmAfterStage0(info,2);                   //第二个农田消耗完继续建造
            }
//            boatMoveToNearLand(info);                                   //运输船靠岸（如果stage1中还有未靠岸的渔船）
//            farmerBoardToBoat(info);                                    //村民上运输船
            if(toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_FARM,info)){
                updateFarm(info);                                       //升级农田
            }
            //仓库升级士兵护甲
            if(toFindTargetBuilding(BUILDING_FARM,info)){
                //仓库对有关技术进行升级，打造强大军队！
                if(!isToBuildATShip(info)&&updateFarmFlag){
                    updateUsetool(info);                                    //仓库升级使用工具
                }
                if((!isToBuildATShip(info))&&UsetoolFlag){
                    updateDefenseInfantry(info);                            //仓库升级步兵护甲
                }
                if((!isToBuildATShip(info))&&UsetoolFlag && DefenseInfantryFlag&&updateFarmFlag){
                    updateDefenceArcher(info);                              //仓库升级弓兵护甲
                }
                if(toFindTargetBuilding(BUILDING_MARKET,info)&&(!isToBuildATShip(info))&&UsetoolFlag
                        &&DefenseInfantryFlag&&DefenseArcherFlag&&updateFarmFlag){
                    updateDefenceRider(info);                               //仓库升级骑兵护甲
                }
            }
            goWork_farming(info);                                       //种田的继续种田
            goWork_cut(info);                                           //继续砍树
            ship_to_fish(info);                                         //继续捕鱼
            if(!isToBuildATShip(info)){
                fightingEnermy(info);                                   //不断攻击敌方战船
            }
            if(info.Wood>=BUILD_FARM_WOOD&&(!toFindTargetBuilding(BUILDING_FARM,info))){
                buildNB_buildings(info,BUILDING_FARM,1);                //农田耗尽时继续建造农田
            }
            if(updateFarmFlag&&toFindTargetBuilding(BUILDING_MARKET,info)){
                updateStone(info);                                      //升级采集石头技术
            }
            if(updateFarmFlag&&toFindTargetBuilding(BUILDING_MARKET,info)){
                updateGold(info);                                       //升级采集金矿技术
            }
    }
}
